package io.github.flypiggy.stack.operate.log.spring.boot.starter.utils;

import io.github.flypiggy.stack.operate.log.spring.boot.starter.exception.OperateLogException;

public class JdbcUrlUtils {

    public static final String STR = "://";

    public static String findDatabaseName(String jdbcUrl) {
        String database;
        int pos, pos1;
        String connUri;
        if (!jdbcUrl.startsWith("jdbc:") || (pos = jdbcUrl.indexOf(STR, 5)) == -1) {
            throw new OperateLogException("Invalid JDBC url.");
        }

        connUri = jdbcUrl.substring(pos + STR.length());

        if ((pos1 = connUri.indexOf('/')) == -1) {
            throw new OperateLogException("Invalid JDBC url. Not found database name!");
        }

        connUri = connUri.substring(pos1 + 1);

        if (connUri.contains("?")) {
            database = connUri.substring(0, connUri.indexOf("?"));
        } else {
            database = connUri;
        }

        if (database.length() == 0) {
            throw new OperateLogException("Invalid JDBC url. Database name is null!");
        }
        return database;
    }

}
